package cn.sunshine.framework.beans.factory.support;

import cn.sunshine.framework.beans.BeansException;
import cn.sunshine.framework.beans.factory.ConfigurableListableBeanFactory;
import cn.sunshine.framework.beans.factory.config.BeanDefinition;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description cn.sunshine.framework.beans.factory.support
 * @Author Mokairui
 * @Since 2021/12/10
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry, ConfigurableListableBeanFactory { // 类适配

    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    // AbstractBeanFactory 的抽象方法
    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws BeansException {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) throw new BeansException("No bean named '" + beanName + "' is defined");
        return beanDefinition;
    }

    // BeanDefinitionRegistry 定义的规范
    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        Map<String, T> result = new HashMap<>();
        beanDefinitionMap.forEach((beanName, BeanDefinition) -> {
            Class beanClass = BeanDefinition.getBeanClass();
            // A.isAssignableFrom(B) A 是 B 的类型或则是 B 的超类 -> true
            if (type.isAssignableFrom(beanClass)) {
                result.put(beanName, (T) getBean(beanName));
            }
        });
        return result;
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }

    // 方法重写至 ConfigurableListableBeanFactory, 为 AbstractApplicationContext 提供初始化 bean 的方法
    @Override
    public void preInstantiateSingletons() throws BeansException {
        beanDefinitionMap.keySet().forEach(this::getBean);
    }

}
